package com.jfinal.dingtalk.api;

import com.jfinal.dingtalk.utils.JsonUtils;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

import java.util.HashMap;
import java.util.Map;

/**
 * 抽象公共api基础
 * Created by L.cm on 2016/6/2.
 */
public abstract class BaseApi {

    /**
     * 构造url
     * @param apiKey api key
     * @param params api参数
     * @return url
     */
    private static String buildApiUrl(String apiKey, Map<String, Object> params) {
        Prop result = PropKit.use("api/dingtalk_api.properties");
        String url = result.get(apiKey);
        return BaseApi.format(url, params);
    }

    /**
     * 专为本业务设计
     *
     * 将字符串中特定模式的字符转换成map中对应的值
     *
     * 替换完成时，清除map中对应的key
     *
     * use: format("my name is {name}, and i like {like}!", {"name":"L.cm", "like": "Java"})
     *
     * @param s		需要转换的字符串
     * @param map	转换所需的键值对集合
     * @return		转换后的字符串
     */
    private static String format(String s, Map<String, Object> map) {
        StringBuilder sb = new StringBuilder((int)(s.length() * 1.5));
        int cursor = 0;
        for (int start, end; (start = s.indexOf("{", cursor)) != -1 && (end = s.indexOf('}', start)) != -1;) {
            sb.append(s.substring(cursor, start));
            String key = s.substring(start + 1, end).trim();
            Object value = map.get(key);
            map.remove(key);
            sb.append(value);
            cursor = end + 1;
        }
        sb.append(s.substring(cursor, s.length()));
        return sb.toString();
    }

    /**
     * aip get请求
     * @param apiKey api key
     * @param data 参数数据
     * @return ApiResult
     */
    protected static ApiResult get(String apiKey, Map<String, Object> data) {
        String url = buildApiUrl(apiKey, data);
        String jsonResult = HttpKit.get(url);
        return ApiResult.create(jsonResult);
    }

    /**
     * 获取AccessToken
     * @param apiKey api key
     * @param data 参数数据
     * @return ApiResult
     */
    protected static AccessToken getAccessToken(String apiKey, Map<String, Object> data) {
        String url = buildApiUrl(apiKey, data);
        String jsonResult = HttpKit.get(url);
        return new AccessToken(jsonResult);
    }

    /**
     * aip post请求
     * @param apiKey api key
     * @param data 参数数据
     * @return ApiResult
     */
    protected static ApiResult post(String apiKey, Map<String, Object> data) {
        String url = buildApiUrl(apiKey, data);
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        String jsonResult = HttpKit.post(url, JsonUtils.toJson(data), headers);
        return ApiResult.create(jsonResult);
    }
}
